package org.elzat.healthboxgatewayapp.filter;

import org.elzat.healthboxgatewayapp.credentials.HealthBoxAuthority;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class HealthBoxGatewayAddRequestHeaderFilter implements GatewayFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return exchange.getPrincipal()
                .switchIfEmpty(Mono.empty())
                .flatMap(principal -> {
                    UsernamePasswordAuthenticationToken token
                            = (UsernamePasswordAuthenticationToken) principal;
                    Collection<GrantedAuthority> auths = token.getAuthorities();
                    String role = "";
                    for (GrantedAuthority auth : auths) {
                        if ((role = auth.getAuthority()).startsWith("role:")) {
                            role = role.substring(5);
                            break;
                        }
                    }
                    ServerHttpRequest request = exchange.getRequest().mutate()
                            .header("user-phone", principal.getName())
                            .header("user-role", role)
                            .build();
                    return chain.filter(exchange.mutate().request(request).build());
                });
    }
}
